<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Guardian extends MY_Parent 
{
	private $students = [];
	private $student_chooser = TRUE;
	private $_user_id = '';

	public function __construct()
	{
		parent::__construct();
		$this->page_auth->secure_page();
		$this->view_data['system_message'] = $this->_msg();
		$this->view_data['underconstruction'] = $this->_msg('n','This Page is Under Construction');
		$this->_user_id = $this->session->userdata('userid');
		$this->load->model(['M_parent','M_system_settings']);
		$this->load->library('hs');
		$this->_get_students_ids();
		$this->_student_chooser();
		$this->view_data['current_url'] = $this->router->class.'/'.$this->router->method.'/';
		$this->view_data['issue_enable'] = $this->issue_enable = $this->M_system_settings->get_setting('student_issues');
		$this->load->helper(['grade','misc','parent']);
	}

	function change_password($id = FALSE)
	{
		$x = $this->hs->decrypt($id);
		$ses_uid = $this->session->userdata('userid');
		$this->load->model('M_users');
		$user = $this->M_users->pull(array('id'=>$ses_uid));
		
		if($x && $x[0] == $ses_uid && $user)
		{
			$this->view_data['system_message'] = $this->_msg();
			$this->view_data['hash'] = $id;
			$this->load->library('form_validation');
			$this->form_validation->set_error_delimiters('<p style="margin:0;padding:0;color:white;font-weight:bold;font-size:12px;">', '</p>');

			if($this->input->post('change_password'))
			{
				$this->load->model('M_users');
				
				$old_pass 	= $this->input->post('old_password');
				$new_pass 	= $this->input->post('new_password');
				$c_new_pass = $this->input->post('c_new_password');
				
				if($this->form_validation->run('user_change_pass') == FALSE)
				{
					// $this->view_data['change_password_errors'] = validation_errors() == '' ? NULL : validation_errors();
					$this->_msg('e', validation_errors(), 'guardian/change_password/'.$id.'#change-password');
				}else
				{	
					$result = $this->M_users->change_pass($old_pass,$new_pass,$x[0],'user');
					
					if($result->stat == TRUE)
					{
						$this->_send_change_password_to_email($user, 'user', $new_pass);
						$message = "<div class='alert alert-success'>{$result->log}</div>";
						$this->_msg('s',$message,'auth/logout/parent');
					}else{
						$this->_msg('e',$result->log,'guardian/change_password/'.$id.'#change-password');
					}
				}
			}else{
				$this->view_data['change_password_errors'] = FALSE;
			}

			if($this->input->post('change_parent_login_username'))
			{
				$this->load->model('M_users');
				
				$this->form_validation->set_rules('new_username', 'username', 'trim|required|xss_clean|callback_username_check');
				$this->form_validation->set_rules('c_new_username', 'confirm username', 'trim|required|xss_clean|matches[new_username]');
				$this->form_validation->set_rules('user_password', 'password', 'trim|required|xss_clean');

				if($this->form_validation->run() == FALSE)
				{
					// $this->view_data['change_username_errors'] = validation_errors() == '' ? NULL : validation_errors();
					$this->_msg('e', validation_errors(), 'guardian/change_password/'.$id.'#change-username');
				}else
				{	
					$post = $this->input->post();
					$uid = $this->session->userdata('userid');
					$result = $this->M_users->change_username($post,$uid,'guardian');

					if($result->status == TRUE)
					{
						$message = "<div class='alert alert-success'>{$result->log}</div>";
						$this->_msg('s',$message,'auth/logout/parent');
					}else{
						$this->_msg('e',$result->log,'guardian/change_password/'.$id.'#change-username');
					}
				}
			}else{
				$this->view_data['change_username_errors'] = FALSE;
			}
		}else{
			show_error('Page not found.',404,'Wait.');
		}
	}

	private function _send_change_password_to_email($val, $usertype, $newpassword)
  {
    $this->load->library('email');
		$this->email->initialize(array( 
		   'mailtype' => 'html', 
		));

		$usertype = $usertype == "parent" ? "guardian" : $usertype;
		$school_name = ucwords($this->school_name);
		$school_name_title = $this->_accronymizer($this->school_name).'@DONOTREPLY.com';
		
		if($this->school_tag_name == FALSE)
		{
			$tagname = 'part of '.$school_name;
		}else{
			$tagname = 'a '.strtoupper($this->school_tag_name);
		}
		
		$this->load->model('M_enrollees');

		$data['school_name'] = $school_name;
		$data['acc'] = $school_name_title;
		$data['link'] = $this->student_link;
		$data['tagname'] = $tagname;
		$data['password'] = $newpassword;
		$data['username'] = $val->username;

		$message = $this->load->view('email_templates/parent_change_password',$data,TRUE);
		
		$this->email->from($school_name_title,$school_name);
		$this->email->to($val->username);
		$this->email->subject('Login Details Updated.');
		$this->email->message($message);
		$this->email->send();	
		
		return true;
  }

	public function username_check($str)
	{
		$this->load->model('M_users');
		$rs = $this->M_users->username_check($str, $this->_user_id);
		if(!$rs){
			$this->form_validation->set_message('username_check', $str.' already exist.');
			return FALSE;
		}

		return true;
	}

	public function index($hash = '')
	{
		$this->layout_view = 'application_guardian';
		$this->view_data['current_id'] = $hash;

		$x = $this->hs->decrypt($hash);
		if($x)
		{
			$id = $x[0];
			$pid = $x[1];
			
			$this->load->model('M_student_grades');
			$this->load->model('M_gperiods');
			$this->load->model('M_enrollees');
			$this->load->model('M_student');
			$this->load->model('M_sections');
			$this->load->model('M_teachers');
			$this->load->model('M_billing_form','mbf');
			$this->load->model('M_student_grades','stud_grades');
			$this->load->model('M_profiles');
			$this->load->model('M_grade_smiley');
			$this->load->model('M_issues');
			
			$this->view_data['grading_periods'] = $this->view_data['gp'] = $this->M_gperiods->get_gperiods();
			$this->view_data['student_all_profiles'] = $this->M_profiles->get_student_full_profile($pid);
			$this->view_data['issues'] = $i = $this->M_issues->get_issues($pid);
			// $this->view_data['student_grades'] = $student_grades = $this->M_student_grades->grouped_subject_by_enrollment_id($id);
			// $this->view_data['student_remarks'] = $this->M_student_grades->get_student_remarks($id);
			// $this->view_data['student_attendance'] = $attendance =$this->M_teachers->get_student_attendance_detailed($id);
			// $this->view_data['section_data'] = $sd = $this->M_sections->get_section_data($id);
			$this->view_data['id'] = $id;
			// $this->view_data['bill_to'] = $this->M_student->get_student($id);
			// $this->view_data['student_billing_form'] = $this->mbf->get_student_billings($id);
			$this->view_data['gd'] = $this->stud_grades->get_grading_system();
			$this->view_data['gs'] = $gs = $this->M_grade_smiley->get_grade_smiley();

			$this->load->model('M_enrollees');
			// $this->view_data['student_subjects'] = $this->M_enrollees->get_all_schedule_by_student_subjects($x[0]);
			// $this->view_data['student_profile'] = $sp = $this->M_enrollees->get_enrollee_prof($x[0]);
			// $this->view_data['schedule'] = TRUE;
			// $this->view_data['enrollments'] = $e = $this->M_enrollees->get_enrollments_prof($pid);


			if(!(empty($student_grades)))
			{
				$this->view_data['grades'] = $this->_loop_throught_grades($student_grades,$id);
			}

			$this->view_data['enrollment_id'] = TRUE;
		}else{
			$this->view_data['enrollment_id'] = FALSE;
		}
	}

	public function soa($hash = "")
	{
		$this->view_data['__page_title'] = "Statement of Account";
		$x = $this->hs->decrypt($hash);
		if($x)
		{
			$e_id = $x[0];
			$pid = $x[1];
			$this->view_data['official_student'] = TRUE;
			$this->load->model(array('M_enrollees','M_scholarships','M_fees'));
			//get student's payment mode
			$this->view_data['payment_mode'] = $this->M_enrollees->get_student_payment_mode($e_id);
			$this->view_data['student_deductions'] = $this->M_scholarships->get_student_deductions($e_id);
			$this->view_data['student_scholarships'] = $this->M_scholarships->get_student_scholarships_deducted($e_id);
			$this->view_data['total_stud_deductions'] = $this->M_scholarships->sum_all_student_deductions($e_id);
			
			$this->view_data['tuit_fees'] = $this->M_enrollees->get_student_fees($e_id,$this->current_school_year,'tuit');
			$this->view_data['misc_fees'] = $this->M_enrollees->get_student_fees($e_id,$this->current_school_year,'misc');
			$this->view_data['cca_fees'] = $this->M_enrollees->get_student_fees($e_id,$this->current_school_year,'cca');
			$this->view_data['elec_fees'] = $this->M_enrollees->get_student_fees($e_id,$this->current_school_year,'elec');
			
			$this->view_data['enrollee_data'] = $enrolle_data = $this->M_enrollees->get_enrollee_prof($e_id);
			$this->view_data['sum_paid_fees'] = $sum_paid_fees = $this->M_enrollees->get_sum_of_paid_fees($e_id,$this->current_school_year);
			$this->view_data['sum_amount_due'] = $sum_amount_due =$this->M_enrollees->get_sum_of_total_payables($e_id,$this->current_school_year);
			$this->view_data['total_payables'] = $this->M_enrollees->get_sum_of_total_payables($e_id,$this->current_school_year);
			$this->view_data['electives_total'] = $electives_total =$this->M_enrollees->get_sum_of_student_electives($e_id,$this->current_school_year);
			$this->view_data['profile_id'] = NULL;
			$this->view_data['enrollment_id'] = $e_id;
			$this->view_data['level_id'] = $this->view_data['enrollee_data']->level_id;
			$this->view_data['foreign_fees_applied'] = $this->M_enrollees->check_student_nationality($e_id,$enrolle_data);
			$this->view_data['eid_enc'] = $this->hs->encrypt(intval($e_id),intval(time()));
			
			$payment_data['amount_due'] = $this->view_data['sum_amount_due'];
			$payment_data['amount_paid'] = $this->view_data['sum_paid_fees'];

			//check if student is fully paid
			$this->_check_student_payment_status($e_id);

		
			// $this->session->set_userdata('payment_data','');
			// $this->session->set_userdata('payment_data',(object)$payment_data);
		}
	}
  
  //displays the breakdown of payment record 
  public function show_payment_breakdown($hash=FALSE,$e_id=FALSE,$p_id=FALSE)
  {
    $this->layout_view = 'application_guardian';
		$this->view_data['current_id'] = $hash;
    $this->load->model('M_student_payment_record');

    if($e_id && $p_id):
      $this->view_data['payments_made'] = $this->M_student_payment_record->get_payment_record_by_enrollment_id($e_id);
			if(!empty($this->view_data['payments_made']))
			{
				$this->view_data['system_message'] = $this->session->flashdata('system_message');
				$e_id = intval($e_id);
				$this->view_data['enrollment_id'] = $e_id;
				$this->view_data['rdate'] = function($x){return date('M d, Y h:i A',strtotime($x));};
				
				if($p_id):
					$this->view_data['payment_breakdown'] = $this->M_student_payment_record->get_payment_breakdown_by_spr_id($p_id);
				endif;
			}else{
				$this->_msg('n','Student has no payment record yet.');
			}
    elseif($hash):
      $this->_msg('n','redirecting...','guardian/index/'.$hash);
    else:
      show_404();
    endif;
  }

	//check if student is fully paid or not
	private function _check_student_payment_status($enrollment_id = '',$sy=FALSE)
	{
		$this->load->model('M_enrollees');
		$this->load->model('M_fees');

		$fps = $this->M_fees->_specific('enrollments','e_fullypaid',['e_id'=>$enrollment_id],TRUE);

		//other payments not in sum_amount_due
		if($sy){
			$electives_total =$this->M_enrollees->get_sum_of_student_electives($enrollment_id,$sy);
		}else{
			$electives_total =$this->M_enrollees->get_sum_of_student_electives($enrollment_id,$this->current_school_year);
		}
		
		//total paid
		if($sy){
			$sum_paid_fees = $this->M_enrollees->get_sum_of_paid_fees($enrollment_id,$sy);
		}else{
			$sum_paid_fees = $this->M_enrollees->get_sum_of_paid_fees($enrollment_id,$this->current_school_year);
		}
		
		//total of payable of student
		if($sy){
			$sum_amount_due =$this->M_enrollees->get_sum_of_total_payables($enrollment_id,$sy);
		}else{
			$sum_amount_due =$this->M_enrollees->get_sum_of_total_payables($enrollment_id,$this->current_school_year);
		}
		
		//students current payment plan
		if($sy){
			$pm =$this->M_enrollees->get_student_payment_mode($enrollment_id,$sy);
		}else{
			$pm =$this->M_enrollees->get_student_payment_mode($enrollment_id);
		}

		$test2 = $this->M_fees->get_student_current_payment_mode_and_due_by_enrollment_id($enrollment_id);

		if($pm !== FALSE )
		{
			if(($sum_amount_due + $electives_total) - $sum_paid_fees <= 0 )
			{
				if($fps->e_fullypaid == 0)
				{
					if($sy){
						$this->M_student_payment_record->update_fully_paid_status($enrollment_id,FALSE,$sy);
					}else{
						$this->M_student_payment_record->update_fully_paid_status($enrollment_id);
					}
				}

				$this->view_data['finance_status'] = $this->_msg('s','Fully Paid');
			}else{
				if($fps->e_fullypaid == 1)
				{
					if($sy){
						$this->M_student_payment_record->update_fully_paid_status($enrollment_id,TRUE,$sy);
					}else{
						$this->M_student_payment_record->update_fully_paid_status($enrollment_id,TRUE);
					}
				}
				$this->view_data['finance_status'] = $this->_msg('n','NOT Fully Paid');
			}
		}else{
			$this->view_data['finance_status'] = $this->_msg('n','Student has no payment plan.');
		}
	}

	public function my_profile()
	{

	}
	
	public function student_profiles($hash = '')
	{
		$this->layout_view = 'application_guardian';
		$x = $this->hs->decrypt($hash);
		$this->view_data['current_id'] = $hash;

		if($x)
		{
			$this->load->model('M_student');
			$this->view_data['student'] = $student = $this->M_student->get_student($x[0]);
			$this->view_data['hid'] = $hash;
			//vd($student);
			$student->edit = 0; // Remove this feature. Added feature - update will only become a request. Registrar will approve / disapproved to apply
			if($student->edit == 0)
			{
				// $this->view_data['system_message'] = $this->_msg('n','This Account is in <i style="color:#f00">Read Only</i>, to edit any data please contact school registrar.');
			}

			if($this->input->post())
			{
				if($student->edit == 0){
					
					$this->view_data['system_message'] = $this->_msg('n','You are not allowed to edit data, <i style="color:#f00">Read Only</i> is activated.');
				}else{


					/*
						I Chopped the process to different forms , why?
						if a user will update just one input field is it really necessary
						to send all fields in the form?
						semperfi. .
					*/

					$_pst = (object)$this->input->post();

					//student profiles tab
					if($this->input->post('update_personal_profile'))
					{

						$res = $this->M_student->_update_personal_profile_data($_pst,$x[0],$student->profile_id);
					}

					//student family history
					if($this->input->post('update_family_history'))
					{
						$res = $this->M_student->_update_family_history_data($_pst,$x[0],$student->profile_id);
					}

					//update developmental history
					if($this->input->post('update_developmental_history'))
					{
						$res = $this->M_student->_update_developmental_history_data($_pst,$x[0],$student->profile_id);
					}

					//update childhood experiences
					if($this->input->post('update_childhood_experiences'))
					{
						$res = $this->M_student->_update_childhood_experiences_data($_pst,$x[0],$student->profile_id);
					}

					//update health history
					if($this->input->post('update_health_history'))
					{
						$res = $this->M_student->_update_health_history_data($_pst,$x[0],$student->profile_id);
					}

					//update discipline
					if($this->input->post('update_discipline'))
					{
						$res = $this->M_student->_update_discipline_data($_pst,$x[0],$student->profile_id);
					}


					if(IS_AJAX)
					{
						$result = ['status'=>$res];
						header('Content-Type: application/json');
						echo json_encode($result);
						exit();
					}
				}
			}
		}
	}

	public function student_grades($hash = '')
	{
		$this->layout_view = 'application_guardian';
		$this->view_data['current_id'] = $hash;

		$x = $this->hs->decrypt($hash);
		if($x)
		{
			$id = $x[0];
			$this->load->model('M_student_grades');
			$this->load->model('M_gperiods');
			$this->load->model('M_enrollees');
			$this->load->model('M_student');
			
			$this->view_data['grading_periods'] = $this->M_gperiods->get_gperiods();
			$this->view_data['student_grades'] = $student_grades = $this->M_student_grades->grouped_subject_by_enrollment_id($id);
			$this->view_data['student_remarks'] = $this->M_student_grades->get_student_remarks($id);
			
			if(!(empty($student_grades)))
			{
				$this->view_data['grades'] = $this->_loop_throught_grades($student_grades,$id);
			}

			$this->view_data['grades_found'] = TRUE;
		}else{
			$this->view_data['grades_found'] = FALSE;
		}
	}

	private function _loop_throught_grades($student_grades, $enrollment_id)
	{
		foreach($student_grades as $row)
		{
		  $result = $this->M_student_grades->get_all_by_enrollment_id($enrollment_id);
		}
		return $result;
	}

	public function student_schedule($hash = '')
	{
		$this->layout_view = 'application_guardian';
		$x = $this->hs->decrypt($hash);
		$this->view_data['current_id'] = $hash;
		
		if($x)
		{
			$this->load->model('M_enrollees');
			$this->view_data['student_subjects'] = $this->M_enrollees->get_all_schedule_by_student_subjects($x[0]);
			$this->view_data['schedule'] = TRUE;
		}
			else
		{
			$this->view_data['schedule'] = FALSE;
		}
	}

	public function student_dmerits()
	{
		$this->layout_view = 'application_guardian';
	}	

	public function student_accounts()
	{
		$this->layout_view = 'application_guardian';
	}


	private function _get_students_ids()
	{
		$userid = $this->session->userdata('userid');
		$this->students = $this->M_parent->get_user_students($userid);
	}

	private function _student_chooser()
	{
		if($this->student_chooser)
		{
			$this->view_data['for_student_chooser']['raw'] = $this->students;
			$this->view_data['for_student_chooser']['student'] = $this->M_parent->students($this->_user_id);
		}
	}
	public function commendations($hash = '')
	{
		$x = $this->hs->decrypt($hash);

		if($x)
		{
			$this->load->library('pagination');
			$this->load->model('M_student','ms');
			$e_id = $x[0];
			
			$config['base_url'] = base_url('guardian/commendations/'.$hash);
			$config['per_page'] = 10;
			$config['uri_segment'] = 4;

			$config['full_tag_open'] = '<div><ul class="pagination">';
			$config['full_tag_close'] = '</ul></div>';

			$config['first_link'] = 'First';
			$config['first_tag_open'] = '<li>';
			$config['first_tag_close'] = '</li>';
			$config['last_link'] = 'Last';
			$config['last_tag_open'] = '<li>';
			$config['last_tag_close'] = '</li>';
			$config['next_link'] = '&gt;';
			$config['next_tag_open'] = '<li>';
			$config['next_tag_close'] = '</li>';
			$config['prev_link'] = '&lt;';
			$config['prev_tag_open'] = '<li>';
			$config['prev_tag_close'] = '</li>';
			$config['cur_tag_open'] = '<li class="current"><a href="">';
			$config['cur_tag_close'] = '</a></li>';
			$config['num_tag_open'] = '<li>';
			$config['num_tag_close'] = '</li>';

			$config['total_rows'] = $this->ms->count_stud_commendations($e_id);
			
			$this->pagination->initialize($config);
			$page = ($this->uri->segment(4)) ? $this->uri->segment(4) : 0;
			// pd($page);
			
			$this->view_data['data']['commendations'] = $this->ms->get_stud_commendations($e_id,$page,$config['per_page']);
			$this->view_data['pagnation_links'] = $this->pagination->create_links();
			// $this->view_data['read_message'] = $this->M_parent->show_message($x[0]);
		}

		$this->layout_view = 'application_guardian';
		$this->view_data['my_students'] = $this->M_parent->get_my_students_commendations($this->_user_id);
		$this->view_data['current_id'] = $hash;
	}

	/**
	 * Parent Request for Profile update
	 */
	public function profile_update_request($hash = '', $req_id_hash = '')
	{
		// $this->layout_view = 'application_guardian';
		$x = $this->hs->decrypt($hash);
		$r = $this->hs->decrypt($req_id_hash);
		$req_id = $r ? $r[0] : false;
		$this->view_data['current_id'] = $hash;
		// vd($this->view_data['for_student_chooser']);
		if($x)
		{
			$this->load->model('M_student');
			$this->load->model('M_parent_profile_updates','m_ppu');
			$student = $r ? $this->m_ppu->get_student($req_id) : $this->M_student->get_student($x[0]);
			$student->edit = $r ? ( $student->status === "PENDING" ? 1 : 0 ) : 1;
			$this->view_data['student'] = $student;
			$this->view_data['hid'] = $hash;
			$this->view_data['req_id'] = $req_id;
			$this->view_data['profile_request'] = true;
			$this->view_data['pid_req_id'] = __link($student->profile_id,$req_id);

			if($this->input->post())
			{
				/*
					I Chopped the process to different forms , why?
					if a user will update just one input field is it really necessary
					to send all fields in the form?
					semperfi. .
				*/

				$_pst = (object)$this->input->post();

				//student profiles tab
				if($this->input->post('update_personal_profile'))
				{

					$res = $this->m_ppu->create_request_personal_profile_data($_pst,$x[0],$student->profile_id, $req_id);
				}

				//student family history
				if($this->input->post('update_family_history'))
				{
					$res = $this->m_ppu->create_request_family_history_data($_pst,$x[0],$student->profile_id, $req_id);
				}

				//update developmental history
				if($this->input->post('update_developmental_history'))
				{
					$res = $this->m_ppu->create_request_developmental_history_data($_pst,$x[0],$student->profile_id, $req_id);
				}

				//update childhood experiences
				if($this->input->post('update_childhood_experiences'))
				{
					$res = $this->m_ppu->create_request_childhood_experiences_data($_pst,$x[0],$student->profile_id, $req_id);
				}

				//update health history
				if($this->input->post('update_health_history'))
				{
					$res = $this->m_ppu->create_request_health_history_data($_pst,$x[0],$student->profile_id, $req_id);
				}

				//update discipline
				if($this->input->post('update_discipline'))
				{
					$res = $this->m_ppu->create_request_discipline_data($_pst,$x[0],$student->profile_id, $req_id);
				}


				if(IS_AJAX)
				{
					$result = ['status'=>$res->status];
					header('Content-Type: application/json');
					echo json_encode($result);
					exit();
				}

				if($res->status){
					$this->_msg('s', $res->msg,'guardian/profile_update_request/'.$hash.'/'.__link($res->req_id));
				}else{
					$this->_msg('e', $res->msg,'guardian/profile_update_request/'.$hash.'/'.__link($res->req_id));
				}
			}
		}
	}

	/**
	 * Update Profile Request by Parent/Guardian
	 */
	public function update_profile_request()
	{
		$this->load->model('M_parent_profile_updates','m_ppu');
		$this->view_data['request'] = $r = $this->m_ppu->get_all_request();
	}

	/**
	 * Remove Profile Update Request
	 * @param string $hash hash ID
	 */
	public function remove_profile_request($hash='')
	{
		$r = $this->hs->decrypt($hash);
		if($r){

			$this->load->model('M_parent_profile_updates','m');

			$rs = $this->m->delete_request($r[0]);

			if($rs){
				$this->_msg('s','Your request was successfully deleted.', 'guardian/update_profile_request');
			}else{
				$this->_msg('e','Your request was not deleted successfully, please try again.', 'guardian/update_profile_request');
			}
		}else{
			show_404();
		}
	}
}

/* End of file parent.php */
/* Location: ./application/controllers/parent.php */